package cn.lee.test.AuthFilter;

import cn.lee.test.model.User;
import cn.lee.test.model.UserToken;
import cn.lee.test.service.UserService;
import cn.lee.test.service.UserTokenService;
import cn.lee.test.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : lichl(李承霖)
 * create: 2022/2/23 20:15 周三
 */

@Component
@Slf4j
public class JwtIntercept implements HandlerInterceptor{
  
  @Autowired
  private UserService userService;
  
  @Autowired
  private UserTokenService tokenService;
  
  // 接口请求处理前调用,在这里写验证登陆状态的业务逻辑
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
    String JWT = request.getHeader("Authorization");
    
    // 校验JWT字符串
    Jws<Claims> decodedJWT = JwtUtils.decode(JWT);
    // 判断当前JTW字符是否和数据库保存的一致
    User loginUser = userService.getLoginUser();
    if(loginUser == null){
      throw new Exception("获取当前登录者失败,拦截器拦截");
    }
    UserToken userToken = tokenService.getTokenByUserId(loginUser.getId());
    
    if(StringUtils.isEmpty(userToken.getTokenString()) || !userToken.getTokenString().equals(JWT)){
      throw new Exception("登录token超时,拦截器拦截");
    }
    return true;
    
  }
}
